package client.view;

/**
 * GameView is the view for the Game object (the local state maintained by Clients).
 * It allows Clients to take actions that affect the state of the Game.
 */
public class GameView extends AbstractView {
	private final java.util.List<ZoneView> zoneViews = new java.util.LinkedList<ZoneView>();
	
	/**
	 * Creates a new GameView for the given Client and Game.
	 * The GameView will use the Client to create Commands
	 * to modify the state of the Game.
	 * @param g the Game 
	 */
	public GameView(core.Game g, client.Client c) {
		super(g, new javax.swing.JPanel(), c);
		popupMenu.add(new UndoAction());
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createGUI();
			}
		});
	}
	
	/**
	 * Lays out the interface of the GameView.
	 */
	private void createGUI() {
		component.setLayout(new FreeformLayout());
		component.setBackground(new java.awt.Color(52,108,56));
		createZoneViews();
		component.setOpaque(true);
	}
	
	/**
	 * Creates the views for the Zones that are represented in the Game.
	 */
	private void createZoneViews() {
		java.awt.Point lastSubViewPoint = new java.awt.Point(0,0);

		// Create all the "public" Zones (that is, the Zones that are 
		// owned by no Players and are children of the Game)
		for (core.Zone zone : client.getGame().getZones()) {
			ZoneView zoneView;
			if (zone instanceof core.OrderedZone)
				zoneView = new OrderedZoneView((core.OrderedZone)zone, client);
			else
				zoneView = new ZoneView(zone, client);
			component.add(zoneView.getComponent()).setLocation(lastSubViewPoint);
			lastSubViewPoint.setLocation(lastSubViewPoint.getX() + 50,
			  lastSubViewPoint.getY() + 50);
			zoneViews.add(zoneView);
		}

		// Create all the "private" Zones (that is, the Zones that are 
		// owned by Players and are children of those Players)
		for (core.Player player : client.getGame().getPlayers()) {
			component.add(new PlayerView(player, client).getComponent()).setLocation(lastSubViewPoint);
			lastSubViewPoint.setLocation(lastSubViewPoint.getX() + 50,
			  lastSubViewPoint.getY() + 50);
		}
	}
	
	private class UndoAction extends javax.swing.AbstractAction 
	{
		public UndoAction() {
			super("Undo", null);
		}
		public void actionPerformed(java.awt.event.ActionEvent arg0) {
			try {
				client.sendCommand(new commands.UndoCommand());
			} catch (java.io.IOException e) {e.printStackTrace();}
		}
	}
}

